//
//  HoTimer.swift
//
//  Created by HOA on 2021/7/12.
//  Copyright © 2020 - 2021 HOA. All rights reserved.
//

import Foundation

open class BaseHoTimer {
    
    public typealias TimerHandler = ((TimeInterval) -> Void)?
    
    private var timer: DispatchSourceTimer!
    
    private var isSuspended = false
    
    private var handler: TimerHandler!
    
    private var date: Date!
    
    init(_ timerInterval: TimeInterval, date: Date!,  handler: TimerHandler) {
        
        if timerInterval > 0 {
            self.date = Date().addingTimeInterval(timerInterval)
        }
        else if let da = date {
            self.date = da
        }
        else {
            fatalError("timerInterval should > 0 OR date != nil")
        }
        
        timer = DispatchSource.makeTimerSource()
        timer.schedule(wallDeadline: .now(), repeating: .milliseconds(1))
        timer.setEventHandler { [weak self] in
            
            guard let self = self, let date = self.date else { return }
            // 是否已经过期
            let seconds = date.timeIntervalSinceNow
            handler?(seconds)
            
            if seconds <= 0 { // 已经过期
                self.remove()
            }
            
        }
        timer.resume()
    }
    
    func remove() {
        timer?.setEventHandler(handler: nil)
        
        handler = nil
        
        timer?.cancel()
    }
    
    deinit {
        debugPrint("\(self) deinit")
    }
}
open class HoTimer: BaseHoTimer {
    
    init(_ timerInterval: TimeInterval,  handler: TimerHandler) {
        super.init(timerInterval, date: nil, handler: handler)
    }
    init(_ date: Date,  handler: TimerHandler) {
        super.init(0, date: date, handler: handler)
    }
}
